package com.ep.common.plugins;

import org.mybatis.generator.api.dom.java.CompilationUnit;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CodeGenerationUtils {

    /**
     * 将生成的代码写入到指定文件中
     *
     * @param compilationUnit 生成的代码单元
     * @param targetProject   目标项目路径
     * @param fileName        文件名
     */
    public static void writeToFile(CompilationUnit compilationUnit, String targetProject, String fileName) {
        try {
            File targetDir = new File(targetProject);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File targetFile = new File(targetDir, fileName);
            FileWriter fileWriter = new FileWriter(targetFile);
            fileWriter.write(compilationUnit.getFormattedContent());
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将下划线分隔的字符串转换为驼峰式命名
     *
     * @param input 输入字符串
     * @return 驼峰式命名的字符串
     */
    public static String toCamelCase(String input) {
        StringBuilder camelCaseString = new StringBuilder();
        boolean nextUpperCase = false;

        for (char c : input.toCharArray()) {
            if (c == '_') {
                nextUpperCase = true; // 下一个字符需要大写
            } else {
                if (nextUpperCase) {
                    camelCaseString.append(Character.toUpperCase(c)); // 大写当前字符
                    nextUpperCase = false;
                } else {
                    camelCaseString.append(c); // 保持当前字符不变
                }
            }
        }

        String camelCaseTableName = camelCaseString.toString();
        camelCaseTableName = camelCaseTableName.substring(0, 1).toUpperCase() + camelCaseTableName.substring(1);

        return camelCaseTableName;
    }

    public static String firstCharToLower(String input) {
        if (input == null || input.isEmpty()) {
            return input; // 如果输入为空或为 null，直接返回
        }
        return Character.toLowerCase(input.charAt(0)) + input.substring(1);
    }
}
